package com.itheima.interceptor;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.itheima.common.R;
import com.itheima.common.TokenHolder;
import com.itheima.constant.TokenConstant;
import com.itheima.pojo.User;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author 小帅蓝
 * @Date 2022/6/23 16:26
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {

    private RedisTemplate<Object, Object> redisTemplate;

    public LoginInterceptor() {
    }

    public LoginInterceptor(RedisTemplate<Object, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.从request中获取token
        String token = request.getHeader("AuthorizationUser");
        //2.判断token是否为空
        if (StrUtil.isNotEmpty(token)) {
            //4.从redis中获取用户信息
            Object json = redisTemplate.opsForValue().get(TokenConstant.USER_TOKEN_PREFIX + token);
            if (ObjectUtil.isNotNull(json)) {
                //取出userId，将userID存入ThreadLocal ,放行
                User user = JSON.parseObject((String) json, User.class);
                if (ObjectUtil.isNotNull(user)) {
                    String id = user.getId();
                    TokenHolder.setCurrentId(id);
                    return true;
                }
            }
        }
        //3.token为空，使用response返回未登录信息
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return false;
    }

}
